package com.mars.diancan.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Cookie工具类
 * @author MARS
 * @date 2018/7/9
 */
public class CookieUtil {

    /**
     * 设置cookie
     * @param response
     * @param name :cookie的key
     * @param value：cookie的value
     * @param maxAge:cookie的过期时间
     */
    public static void set(HttpServletResponse response,
                           String name,
                           String value,
                           int maxAge){
        Cookie cookie = new Cookie(name,value);
        // cookie种的域名
        cookie.setPath("/");
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }

    /**
     * 将cookie封装成map
     * @param request
     */
    private static Map<String,Cookie> readCookieMap(HttpServletRequest request){
        Map<String,Cookie> map = new HashMap<>();
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            for(Cookie cookie : cookies){
                map.put(cookie.getName(),cookie);
            }
        }
        return map;
    }

    /**
     * 获取cookie
     */
    public static Cookie get(HttpServletRequest request,String name) {
        Map<String,Cookie> map = readCookieMap(request);
        if(map.containsKey(name)){
            return map.get(name);
        } else {
            return null;
        }
    }
}
